package qeug.shsh.facde.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import com.drew.lang.annotations.NotNull;
import kd.bos.dataentity.OperateOption;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.openapi.common.custom.annotation.*;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import qeug.shsh.facde.info.CustomerInfo;
import qeug.shsh.facde.resultext.CustomerResultExt;
import qeug.shsh.helper.FacadeHelper;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 客户api接口
 * @description: 客户api接口
 */
@ApiController(value = "CustomerController", desc = "金蝶客户接口，自定义插件")
public class CustomerController implements Serializable {

    @ApiPostMapping(value = "/shsh_customer", desc = "客户api接口")
    public CustomApiResult<@ApiResponseBody("返回参数") CustomerResultExt> SHCustomer
            (@NotNull @ApiParam(value = "入参") CustomerInfo model) {
        /*
          返回值对象
         */
        CustomerResultExt customerResultExt = new CustomerResultExt();
        int failCount = 0;//失败数量
        int successCount = 0;//成功数量
        /*
          返回信息
         */
        ArrayList<CustomerResultExt.ResultBean> results = new ArrayList<>();
        /*
          接口日志
         */
        StringBuilder msgBuilder = new StringBuilder();

        List<CustomerInfo.DataBean> data = model.getData();
        for (int i = 0; i < data.size(); i++) {
//            StringBuffer stringBuffer = new StringBuffer();//错误信息提示
            CustomerInfo.DataBean dataBean = data.get(i);
            String id = dataBean.getMDM_NO();//分发id
            String number = dataBean.getKUNNR();//客户编码
            String status = dataBean.getSTATUS();//使用状态
            if (StringUtils.isBlank(number)) {
                msgBuilder.append("第").append(i + 1).append("条数据，编码为空不能保存!");
                CustomerResultExt.ResultBean failure = CustomerResultExt.failure(i, "客户编码不能为空", id);
                results.add(failure);//将返回结果数据存放到集合中
                customerResultExt.setResult(results);//将集合重新传给返回值参数
                failCount++;//错误信息+1
            } else {
                // 检查编码是否存在
                DynamicObject existingCustomer = BusinessDataServiceHelper.loadSingle("bd_customer", new QFilter("number", "=", number).toArray());
                String message = null;
                if (existingCustomer != null && "1".equals(status)) {
                    // 编码已存在，执行修改操作
                    DynamicObject customer = existingCustomer;
                    customer.set("enable", dataBean.getSTATUS());//使用状态
                    customer.set("status", "C");//数据状态默认已审核
                    String fullName = dataBean.getFULL_NAME();
                    if (StringUtils.isBlank(fullName)) {
                        DynamicObject full = BusinessDataServiceHelper.loadSingle("bd_customer", new QFilter("number", "=", number).toArray());
                        fullName = full.getString("name");
                    }
                    customer.set("name", fullName);//单位全称
                    customer.set("simplename", dataBean.getNAME1());//单位简称
                    customer.set("internal_company", FacadeHelper.getDynamicObject("bos_org", "name", dataBean.getVBUND()));//贸易伙伴（内部单位）
                    customer.set("bizpartner_address", dataBean.getADDRESS());//地址
                    customer.set("bizpartner_phone", dataBean.getTEL_NUMBER());//电话号
                    customer.set("bizpartner_fax", dataBean.getFAX_NUMBER());//传真号
                    customer.set("societycreditcode", dataBean.getSORT1());//统一信用代码
                    String land1 = dataBean.getLAND1();//国家编码
                    customer.set("country", BusinessDataServiceHelper.loadSingle("bd_country", new QFilter("twocountrycode", "=", land1).toArray()));//国家编码
                    if (land1 == null) {
                        String land2 = dataBean.getLAND2();//国家名称
                        customer.set("country", BusinessDataServiceHelper.loadSingle("bd_country", new QFilter("name", "=", land2).toArray()));//国家名称
                    }
                    customer.set("postal_code", dataBean.getEMAIL());//电子邮箱

                    //输入只有地区名称、编码，输出为只有地区名称
                    //输入有城市名称、编码和地区名称、编码，输出为城市名称和地区名称；
                    String regio = dataBean.getREGIO();//地区编码
                    String regio1 = dataBean.getREGIO1();//地区名称
                    String ort02 = dataBean.getORT02();//城市编码
                    String ort01 = dataBean.getORT01();//城市名称
                    if (StringUtils.isNotBlank(ort01) || StringUtils.isNotBlank(ort02)) {
                        if (StringUtils.isNotBlank(ort01)) {
                            QFilter f1 = new QFilter("name", QCP.equals, ort01);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                customer.set("admindivision", collection.get("id"));
                            }
                        } else {
                            QFilter f1 = new QFilter("number", QCP.equals, ort02);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                customer.set("admindivision", collection.get("id"));
                            }
                        }
                    } else {
                        if (StringUtils.isNotBlank(regio1)) {
                            //不为空且不为null
                            QFilter f1 = new QFilter("name", QCP.equals, regio1);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                customer.set("admindivision", collection.get("id"));
                            }
                        } else {
                            QFilter f1 = new QFilter("number", QCP.equals, regio);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                customer.set("admindivision", collection.get("id"));
                            }
                        }
                    }

                    List<CustomerInfo.DataBean.EntrySort> sorts = dataBean.getSorts();//分类标准
                    if (sorts != null) {
                        DynamicObjectCollection groupstandardCollection = customer.getDynamicObjectCollection("entry_groupstandard");//分类标准
                        DynamicObjectType groupstandardType = groupstandardCollection.getDynamicObjectType();
                        CustomerInfo.DataBean.EntrySort entrySort = sorts.get(0);
                        DynamicObject SortEntry = new DynamicObject(groupstandardType);
                        String ktokk = entrySort.getKTOKD();//客户账户组代码
                        DynamicObject supplierGroupNumber = FacadeHelper.getDynamicObject("bd_customergroup", "number", ktokk);
                        DynamicObject customergroupstandard = BusinessDataServiceHelper.loadSingle("bd_customergroupstandard", new QFilter("number", "=", "JBFLBZ").toArray());
                        SortEntry.set("groupid", supplierGroupNumber);//客户账户组代码
                        SortEntry.set("standardid",customergroupstandard);//客户分类标准
                        if (ktokk == null) {
                            String ktokk1 = entrySort.getKTOKD1();//客户账户组名称
                            DynamicObject supplierGroupName = FacadeHelper.getDynamicObject("bd_customergroup", "name", ktokk1);
                            SortEntry.set("groupid", supplierGroupName);//客户账户组名称
                            SortEntry.set("standardid",customergroupstandard);//客户分类标准
                        }
                        groupstandardCollection.add(SortEntry);
                    }

                    List<CustomerInfo.DataBean.EntryBanks> banks = dataBean.getBanks();//银行分录
                    DynamicObjectCollection banksCollection = customer.getDynamicObjectCollection("entry_bank");//银行分录
                    // 移除现有的银行分录
                    banksCollection.clear();
                    DynamicObjectType bankType = banksCollection.getDynamicObjectType();
                    for (int k = 0; k < banks.size(); k++) {
                        CustomerInfo.DataBean.EntryBanks entryBanks = banks.get(k);
                        DynamicObject banksEntry = new DynamicObject(bankType);
                        //同一个银行账号 不能同时存在在不同编码的客商内
                        String bankn = entryBanks.getBANKN();
                        if (bankn != null) {
                            // 检查银行账号是否已存在于其他编码中
                            //为true银行账号已存在于其他编码中，为false 银行账号不存在于其他编码中
                            boolean isBankAccountExists = checkBankAccountExists(bankn);
                            if (!isBankAccountExists) {
                                //现在为false
                                banksEntry.set("bankaccount", bankn);//银行账号
                            } else {
                                //现在为true
                                DynamicObject bill1 = BusinessDataServiceHelper.loadSingle("bd_customer", new QFilter("entry_bank.bankaccount", "=", bankn).toArray());
                                String number2 = bill1.getString("number");
                                if (number2.equals(number)) {
                                    banksEntry.set("bankaccount", bankn);//银行账号
                                } else {
                                    msgBuilder.append("第").append(i + 1).append("条数据，银行账号重复，不能保存!");
                                    CustomerResultExt.ResultBean failure = CustomerResultExt.failure(i, "银行账号已存在于其他编码中", id);
                                    results.add(failure);//将返回结果数据存放到集合中
                                    customerResultExt.setResult(results);//将集合重新传给返回值参数
                                    failCount++;//错误信息+1
                                }
                            }
                        }
                        String koinh = entryBanks.getKOINH();
                        banksEntry.set("accountname", koinh);//开户账户名(账户名称)
                        String currencyNum = entryBanks.getCURRENCYCODE();//币种代码
                        DynamicObject currencyNumber = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("Number", "=", currencyNum).toArray());
                        banksEntry.set("currency", currencyNumber);//币种代码
                        if (currencyNum == null) {
                            String currencyname = entryBanks.getCURRENCYNAME();//币种名称
                            DynamicObject currencyName = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("name", "=", currencyname).toArray());
                            banksEntry.set("currency", currencyName);//币种名称
                        }
                        String bankl = entryBanks.getBANKL(); //开户银行通过联行号获取
                        DynamicObject bank = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("union_number", "=", bankl).toArray());
                        banksEntry.set("bank", bank);//开户银行
                        if (bankl == null) {
                            String bankName1 = entryBanks.getBANKN();//开户银行名称
                            DynamicObject bankName2 = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("name", "=", bankName1).toArray());
                            banksEntry.set("bank", bankName2);//开户银行名称
                        }
                        String iban = entryBanks.getBANKS();
                        banksEntry.set("iban", iban);//银行国家代码（国际银行账户号码）
                        //第一行银行信息为默认
                        if (k == 0) {
                            banksEntry.set("isdefault_bank", true);//默认
                        } else {
                            banksEntry.set("isdefault_bank", false);
                        }
                        banksCollection.add(banksEntry);
                    }
                    OperationResult bd_customer = OperationServiceHelper.executeOperate("save", "bd_customer", new DynamicObject[]{customer});
                    for (IOperateInfo errInfo : bd_customer.getAllErrorOrValidateInfo()) {
                        message = errInfo.getMessage();
                    }
                    System.out.println();
                } else if ("0".equals(status)) {
                    //使用状态为0，不接受新增和修改
                    msgBuilder.append("第").append(i + 1).append("条数据，使用状态为停用，不接受新增和修改!");
                    CustomerResultExt.ResultBean failure = CustomerResultExt.failure(i, "使用状态为停用，不接受新增和修改", id);
                    results.add(failure);//将返回结果数据存放到集合中
                    customerResultExt.setResult(results);//将集合重新传给返回值参数
                    failCount++;
                    customerResultExt.setFailCount(failCount);//失败数量
                } else {
                    String fullName = dataBean.getFULL_NAME();//单位全称
                    if (StringUtils.isBlank(fullName)) {
                        msgBuilder.append("第").append(i + 1).append("条数据，编码为空不能保存!");
                        CustomerResultExt.ResultBean failure = CustomerResultExt.failure(i, "客户编码不能为空", id);
                        results.add(failure);//将返回结果数据存放到集合中
                        customerResultExt.setResult(results);//将集合重新传给返回值参数
                        failCount++;//错误信息+1
                    }
                    String forShort = dataBean.getNAME1();//单位简称
                    String createOrg = dataBean.getCREATEORG("盛虹集团");//创建组织“默认盛虹集团”
                    DynamicObject createOrgName = BusinessDataServiceHelper.loadSingle("bos_adminorg", new QFilter("name", "=", createOrg).toArray());
                    String address = dataBean.getADDRESS();//地址
                    String land1 = dataBean.getLAND1();//国家编码
                    DynamicObject landNumber = BusinessDataServiceHelper.loadSingle("bd_country", new QFilter("twocountrycode", "=", land1).toArray());
                    String vbund = dataBean.getVBUND();//贸易伙伴（内部单位）
                    DynamicObject vbundName = FacadeHelper.getDynamicObject("bos_org", "name", vbund);
                    String tel_number = dataBean.getTEL_NUMBER();//电话号
                    String fax_number = dataBean.getFAX_NUMBER();//传真号
                    String sort1 = dataBean.getSORT1();//统一信用代码
                    String email = dataBean.getEMAIL();//电子邮件

                    ORM orm = ORM.create();
                    DynamicObject customer = orm.newDynamicObject("bd_customer");
                    customer.set("number", number);//编码
                    customer.set("name", fullName);//单位全称
                    customer.set("simplename", forShort);//单位简称
                    customer.set("enable", status);//使用状态
                    customer.set("status", "C");//数据状态默认已审核
                    customer.set("createorg", createOrgName);//创建组织
                    customer.set("ctrlstrategy", "2");//控制策略“默认自由分配”
                    customer.set("internal_company", vbundName);//贸易伙伴（内部单位）
                    customer.set("bizpartner_address", address);//地址
                    customer.set("bizpartner_phone", tel_number);//电话号
                    customer.set("bizpartner_fax", fax_number);//传真号
                    customer.set("societycreditcode", sort1);//统一信用代码
                    customer.set("country", landNumber);//国家编码
                    if (land1 == null) {
                        String land2 = dataBean.getLAND2();//国家名称
                        DynamicObject landName = BusinessDataServiceHelper.loadSingle("bd_country", new QFilter("name", "=", land2).toArray());
                        customer.set("country", landName);//国家名称
                    }
                    customer.set("postal_code", email);//电子邮箱
                    customer.set("enabler", "1");//是否可用
                    //输入只有地区名称、编码，输出为只有地区名称
                    //输入有城市名称、编码和地区名称、编码，输出为城市名称和地区名称；
                    String regio = dataBean.getREGIO();//地区编码
                    String regio1 = dataBean.getREGIO1();//地区名称
                    String ort02 = dataBean.getORT02();//城市编码
                    String ort01 = dataBean.getORT01();//城市名称
                    if (StringUtils.isNotBlank(ort01) || StringUtils.isNotBlank(ort02)) {
                        if (StringUtils.isNotBlank(ort01)) {
                            QFilter f1 = new QFilter("name", QCP.equals, ort01);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                customer.set("admindivision", collection.get("id"));
                            }
                        } else {
                            QFilter f1 = new QFilter("number", QCP.equals, ort02);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                customer.set("admindivision", collection.get("id"));
                            }
                        }
                    } else {
                        if (StringUtils.isNotBlank(regio1)) {
                            //不为空且不为null
                            QFilter f1 = new QFilter("name", QCP.equals, regio1);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                customer.set("admindivision", collection.get("id"));
                            }
                        } else {
                            QFilter f1 = new QFilter("number", QCP.equals, regio);
                            DynamicObjectCollection collections = QueryServiceHelper.query("bd_admindivision", "id,number,name,level,fullname", new QFilter[]{f1});
                            for (DynamicObject collection : collections) {
                                customer.set("admindivision", collection.get("id"));
                            }
                        }
                    }

                    List<CustomerInfo.DataBean.EntrySort> sorts = dataBean.getSorts();//分类标准
                    if (sorts != null) {
                        DynamicObjectCollection groupstandardCollection = customer.getDynamicObjectCollection("entry_groupstandard");//分类标准
                        DynamicObjectType groupstandardType = groupstandardCollection.getDynamicObjectType();
                        CustomerInfo.DataBean.EntrySort entrySort = sorts.get(0);
                        DynamicObject SortEntry = new DynamicObject(groupstandardType);
                        String ktokk = entrySort.getKTOKD();//客户账户组代码
                        DynamicObject supplierGroupNumber = FacadeHelper.getDynamicObject("bd_customergroup", "number", ktokk);
                        DynamicObject customergroupstandard = BusinessDataServiceHelper.loadSingle("bd_customergroupstandard", new QFilter("number", "=", "JBFLBZ").toArray());
                        SortEntry.set("groupid", supplierGroupNumber);//客户账户组代码
                        SortEntry.set("standardid",customergroupstandard);//客户分类标准
                        if (ktokk == null) {
                            String ktokk1 = entrySort.getKTOKD1();//客户账户组名称
                            DynamicObject supplierGroupName = FacadeHelper.getDynamicObject("bd_customergroup", "name", ktokk1);
                            SortEntry.set("groupid", supplierGroupName);//客户账户组名称
                            SortEntry.set("standardid",customergroupstandard);//客户分类标准
                        }
                        groupstandardCollection.add(SortEntry);
                    }

                    List<CustomerInfo.DataBean.EntryBanks> banks = dataBean.getBanks();//银行分录
                    if (banks == null) {
                        msgBuilder.append("第").append(i + 1).append("条数据，银行分录为空不能保存!");
                        CustomerResultExt.ResultBean failure = CustomerResultExt.failure(i, "银行分录不能为空", id);
                        results.add(failure);//将返回结果数据存放到集合中
                        customerResultExt.setResult(results);//将集合重新传给返回值参数
                        failCount++;//错误信息+1
                    } else {
                        DynamicObjectCollection banksCollection = customer.getDynamicObjectCollection("entry_bank");//银行分录
                        DynamicObjectType bankType = banksCollection.getDynamicObjectType();
                        for (int k = 0; k < banks.size(); k++) {
                            CustomerInfo.DataBean.EntryBanks entryBanks = banks.get(k);
                            DynamicObject banksEntry = new DynamicObject(bankType);
                            //同一个银行账号 不能同时存在在不同编码的客商内
                            String bankn = entryBanks.getBANKN();
                            if (bankn != null) {
                                // 检查银行账号是否已存在于其他编码中
                                boolean isBankAccountExists = checkBankAccountExists(bankn);
                                if (!isBankAccountExists) {
                                    banksEntry.set("bankaccount", bankn);//银行账号
                                } else {
                                    msgBuilder.append("第").append(i + 1).append("条数据，银行账号重复，不能保存!");
                                    CustomerResultExt.ResultBean failure = CustomerResultExt.failure(i, "银行账号已存在于其他编码中", id);
                                    results.add(failure);//将返回结果数据存放到集合中
                                    customerResultExt.setResult(results);//将集合重新传给返回值参数
                                    failCount++;//错误信息+1
                                }
                            }
                            String koinh = entryBanks.getKOINH();
                            banksEntry.set("accountname", koinh);//开户账户名(账户名称)
                            String currencyNum = entryBanks.getCURRENCYCODE();//币种代码
                            DynamicObject currencyNumber = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("Number", "=", currencyNum).toArray());
                            banksEntry.set("currency", currencyNumber);//币种代码
                            if (currencyNum == null) {
                                String currencyname = entryBanks.getCURRENCYNAME();//币种名称
                                DynamicObject currencyName = BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter("name", "=", currencyname).toArray());
                                banksEntry.set("currency", currencyName);//币种名称
                            }
                            String bankl = entryBanks.getBANKL(); //开户银行通过联行号获取
                            DynamicObject bank = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("union_number", "=", bankl).toArray());
                            banksEntry.set("bank", bank);//开户银行
                            if (bankl == null) {
                                String bankName1 = entryBanks.getBANKN();//开户银行名称
                                DynamicObject bankName2 = BusinessDataServiceHelper.loadSingle("bd_bebank", new QFilter("name", "=", bankName1).toArray());
                                banksEntry.set("bank", bankName2);//开户银行名称
                            }
                            String iban = entryBanks.getBANKS();
                            banksEntry.set("iban", iban);//银行国家代码（国际银行账户号码）
                            //第一行银行信息为默认
                            if (k == 0) {
                                banksEntry.set("isdefault_bank", true);//默认
                            } else {
                                banksEntry.set("isdefault_bank", false);
                            }
                            banksCollection.add(banksEntry);
                        }
                        OperationResult bd_customer = SaveServiceHelper.saveOperate("bd_customer", new DynamicObject[]{customer}, OperateOption.create());
                        System.out.println();
                        for (IOperateInfo errInfo : bd_customer.getAllErrorOrValidateInfo()) {
                            message = errInfo.getMessage();
                        }
                    }
                }
                CustomerResultExt.ResultBean resultbean = new CustomerResultExt.ResultBean();
                resultbean.setErrors(Collections.singletonList(message));
                if (message != null) {
                    resultbean.setNumber(id);
                    results.add(resultbean);
                    failCount++;
                }
            }
        }
        if (failCount < data.size()) {
            successCount = data.size() - failCount;//成功数量
        }
        customerResultExt.setResult(results);//返回错误结果
        customerResultExt.setFailCount(failCount);//失败数量
        customerResultExt.setSuccessCount(successCount);//成功数量
        return CustomApiResult.success(customerResultExt);
    }

    private boolean checkBankAccountExists(String bankn) {
        DynamicObject bill = BusinessDataServiceHelper.loadSingle("bd_customer", new QFilter("entry_bank.bankaccount", "=", bankn).toArray());
        if (bill != null) {
            return true; // 银行账号已存在于其他编码中
        }
        return false;// 银行账号不存在于其他编码中
    }
}
